#encoding:utf-8

from django.http import HttpResponse,HttpResponseRedirect
from django.core.paginator import PageNotAnInteger, Paginator, InvalidPage, EmptyPage
from django.core.urlresolvers import reverse
from django.shortcuts import render
from rewards.models import Reward,Uncover,Reward_mes
from courses.models import Types,Tiny_type,Course,Lession,Course_comment
from users.models import Warning_mes,Info,Teacher,News,Review_of_news,Message,Follow_topic,Follow_user,Follow_group,Follow_course,Post_reward,Post_course,Purchase,Good_news,Good_review_of_news
from django.utils import timezone
from remind import warn
import re,md5,os,time,random,base64,math

#悬赏的主页
def reward(request):
	if not 'id' in request.session:
		return HttpResponseRedirect(reverse('login:index'))
	types=Types.objects.all()
	#获取所有没有成交的悬赏保存在rewards列表中
	rewardTable=Reward.objects.filter(status=0).order_by('-time')
	rewards=[]
	for r in rewardTable:
		areward=[]
		i=Info.objects.get(user_id=r.from_id)
		areward.append(i.img)			#0
		areward.append(r.id)			#1
		areward.append(r.name[0:12]+'...')		#2
		areward.append(r.price)		#3
		intro=r.introduce[0:70]
		intro=intro+'...'
		areward.append(intro)			#4
		typesTable=Types.objects.get(id=r.types_id)
		areward.append(typesTable.name)	#5
		areward.append(i.domain)		#6
		rewards.append(areward)
	#分页
	paginator = Paginator(rewards, 15)
	page = request.GET.get('page')
	try:
	    rewards = paginator.page(page)
	except PageNotAnInteger:
	    rewards = paginator.page(1)
	except EmptyPage:
	    rewards = paginator.page(paginator.num_pages)
	result=[]
	waningMes=warn(request.session['id'])[0]
	havent=warn(request.session['id'])[1]
	mess=warn(request.session['id'])[2]
	info=Info.objects.get(user_id=request.session['id'])
	#热门的悬赏,根据留言数来获取
	hotRewardTable=Reward.objects.filter(status=0).order_by('-message_con')[0:5]
	return render(request,'rewards/rewards.html',{'hotRewardTable':hotRewardTable,'rewards':rewards,'types':types,'info':info,'waningMes':waningMes,'havent':havent,'message':mess})

"""
针对reward的检索（包括：按照悬赏的大分类检索 & 按照时间、价格、人气检索）
order为时间、价格、人气；typeid为大分类id
"""
def rewards(request):
	if not 'id' in request.session:
		return HttpResponseRedirect(reverse('login:index'))
	if 'order' in request.GET:
		order=int(request.GET['order'])
	else:
		order=0

	if 'typeid' in request.GET:
		typeid=int(request.GET['typeid'])
	else:
		typeid=0
	
	types=Types.objects.all()

	if typeid==0:
		if order==4:
			rewardTable=Reward.objects.filter(status=0).order_by('price')
		elif order==3:
			rewardTable=Reward.objects.filter(status=0).order_by('-price')
		elif order==2:
			rewardTable=Reward.objects.filter(status=0).order_by('-message_con')
		else:
			rewardTable=Reward.objects.filter(status=0).order_by('-time')
	else:
		if order==4:
			rewardTable=Reward.objects.filter(status=0).filter(types_id=int(typeid)).order_by('price')
		elif order==3:
			rewardTable=Reward.objects.filter(status=0).filter(types_id=int(typeid)).order_by('-price')
		elif order==2:
			rewardTable=Reward.objects.filter(status=0).filter(types_id=int(typeid)).order_by('-message_con')
		else:
			rewardTable=Reward.objects.filter(status=0).filter(types_id=int(typeid)).order_by('-time')
	rewards=[]
	for r in rewardTable:
		areward=[]
		i=Info.objects.get(user_id=r.from_id)
		areward.append(i.img)		#0
		areward.append(r.id)			#1
		areward.append(r.name[0:12]+'...')		#2
		areward.append(r.price)		#3
		intro=r.introduce[0:70]
		intro=intro+'...'
		areward.append(intro)			#4
		typesTable=Types.objects.get(id=r.types_id)
		areward.append(typesTable.name)	#5
		areward.append(i.domain)		#6	
		rewards.append(areward)
	paginator = Paginator(rewards, 15)
	page = request.GET.get('page')
	try:
	    rewards = paginator.page(page)
	except PageNotAnInteger:
	    rewards = paginator.page(1)
	except EmptyPage:
	    rewards = paginator.page(paginator.num_pages)
	result=[]
	waningMes=warn(request.session['id'])[0]
	havent=warn(request.session['id'])[1]
	mess=warn(request.session['id'])[2]
	info=Info.objects.get(user_id=request.session['id'])

	hotRewardTable=Reward.objects.filter(status=0).order_by('-message_con')[0:5]
	return render(request,'rewards/rewards.html',{'hotRewardTable':hotRewardTable,'rewards':rewards,'types':types,'waningMes':waningMes,'havent':havent,'order':order,'typeid':typeid,'info':info,'message':mess})


#发布新的悬赏页面
def rewardcreate(request):
	if not 'id' in request.session:
		return HttpResponseRedirect(reverse('login:index'))
	info=Info.objects.get(user_id=request.session['id'])
	user_name=info.user_name
	user_img=info.img
	types=Types.objects.all()
	rewardscount=Reward.objects.filter(from_id=request.session['id']).count()
	waningMes=warn(request.session['id'])[0]
	havent=warn(request.session['id'])[1]
	mess=warn(request.session['id'])[2]
	return render(request,'rewards/rewardCreate.html',{'info':info,'types':types,'waningMes':waningMes,'havent':havent,'user_name':user_name,'user_img':user_img,'user_id':request.session['id'],'rewardscount':rewardscount,'message':mess})

#发布新的悬赏后台
def addReward(request):
	if not 'id' in request.session:
		return HttpResponseRedirect(reverse('login:index'))
	course_name=request.POST['course_name']
	course_intro=request.POST['course_intro']
	price=request.POST['price']
	belongtype=request.POST['belongtype']
	reward=Reward(types_id=request.POST['belongtype'],from_id=request.session['id'],name=request.POST['course_name'],introduce=request.POST['course_intro'],price=request.POST['price'],course_id=0)
	reward.save()
	#reward的截止日期,30 days
	reward.deadline_str=str(reward.deadline)
	reward_list=reward.deadline_str.split('.')
	deadline_str=reward_list[0]
	timeArray=time.strptime(deadline_str,"%Y-%m-%d %H:%M:%S")
	timeStamp=int(time.mktime(timeArray))
	x = time.localtime(timeStamp+2592000)
	reward.deadline=time.strftime('%Y-%m-%d %H:%M:%S',x)
	reward.save()
	#将这条新鲜事存储
	user_id=int(request.session['id'])
	content='发布了悬赏<a href="/rewards/the/'+str(reward.id)+'">'+str(request.POST['course_name'])+'</a>'
	news=News(user_id=user_id,content=content,good_con=0,share_con=0,review_con=0)
	news.save()

	#return HttpResponseRedirect('../success/?course_name='+course_name+'&reward_id='+str(reward.id))
	return HttpResponseRedirect('../the/'+str(reward.id))


def success(request):
	if not 'id' in request.session:
		return HttpResponseRedirect(reverse('login:index'))
	course_name=request.GET['course_name']
	reward_id=int(request.GET['reward_id'])
	return render(request,'rewards/success.html',{'course_name':course_name,'reward_id':reward_id})

#某一个悬赏
def thereward(request,id):
	if not 'id' in request.session:
		return HttpResponseRedirect(reverse('login:index'))
	thereward=Reward.objects.get(id=id)
	info=Info.objects.get(user_id=thereward.from_id)
	#将悬赏的内容存储在areward列表中
	areward=[]
	areward.append(thereward.name)		#0
	areward.append(thereward.introduce)		#1
	areward.append(thereward.time)		#2
	areward.append(thereward.deadline)		#3
	areward.append(thereward.price)		#4
	areward.append(info.user_name)		#5
	areward.append(info.img)			#6
	Rcount = Reward.objects.filter(from_id=info.user_id).count()
	areward.append(Rcount)			#7
	SUCRcount = Reward.objects.filter(from_id=info.user_id).filter(to__isnull=False).count()
	areward.append(SUCRcount)			#8
	typesTable=Types.objects.get(id=thereward.types_id)
	areward.append(typesTable.name)		#9
	areward.append(id)				#10
	areward.append(info.domain)			#11
	areward.append(info.user_id)		#12
	re_rewardTable=Reward_mes.objects.filter(reward_id=id).order_by('-time')
	#某条悬赏的评论存储在re_rewards列表中
	re_rewards=[]
	for r in re_rewardTable:
		a_re_reward=[]
		info=Info.objects.get(user_id=r.from_id)
		a_re_reward.append(info.img)			#0
		a_re_reward.append(info.user_name)		#1
		a_re_reward.append(r.content)			#2
		a_re_reward.append(r.time)			#3
		a_re_reward.append(r.from_id)			#4
		a_re_reward.append(info.domain)		#5
		a_re_reward.append(r.id)		#6
		re_rewards.append(a_re_reward)
	#是否已经有人揭榜
	if Uncover.objects.filter(reward_id=id).filter(to=request.session['id']):
		uncover_exist=1
	else:
		uncover_exist=0
	#评分
	yellow_stars=range(0,info.credit)
	hollow_stars=range(0,(5-info.credit))
	info=Info.objects.get(user_id=request.session['id'])
	enreward=base64.encodestring(str(thereward.id))
	enuser=base64.encodestring(str(request.session['id']))
	ento=base64.encodestring(str(thereward.from_id))
	#status:0,尚未被揭榜过;1,如果我是揭榜者揭榜者,尚未创建课程;2,课程已经创建;3,悬赏被揭榜过，但没有成交;4,如果我是悬赏的发布者,悬赏的课程尚未创建
	if int(request.session['id'])==thereward.to:
		if int(thereward.course_id)==0:
			status=1
		else:
			status=2
	elif int(request.session['id'])==int(thereward.from_id):
		if int(thereward.course_id)==0:
			status=4
		else:
			status=2
	elif Uncover.objects.filter(to=request.session['id']).filter(reward_id=thereward.id):
			status=3
	else:
			status=0
	paginator = Paginator(re_rewards, 15)
	page = request.GET.get('page')
	try:
	    re_rewards = paginator.page(page)
	except PageNotAnInteger:
	    re_rewards = paginator.page(1)
	except EmptyPage:
	    re_rewards = paginator.page(paginator.num_pages)
	waningMes=warn(request.session['id'])[0]
	havent=warn(request.session['id'])[1]
	mess=warn(request.session['id'])[2]
	return render(request,'rewards/theReward.html',{'status':status,'waningMes':waningMes,'havent':havent,'enreward':enreward,'enuser':enuser,'ento':ento,'areward':areward,'info':info,'re_rewards':re_rewards,'yellow_stars':yellow_stars,'hollow_stars':hollow_stars,'uncover_exist':uncover_exist,'thereward':thereward,'publisher':thereward.from_id,'message':mess,'r_id':id})

#添加评论
def addreview(request):
	content=request.GET['content']
	reward_id=request.GET['reward_id']
	from_id=request.session['id']
	re_reward=Reward_mes(reward_id=reward_id,from_id=from_id,content=content)
	re_reward.save()
	rewardTable=Reward.objects.get(id=reward_id)
	to=rewardTable.from_id
	rewardTable.message_con=int(rewardTable.message_con)+int(1)
	rewardTable.save()
	info=Info.objects.get(user_id=from_id)
	#添加一条提醒
	warning_mesTable=Warning_mes(from_id=int(from_id),to=int(to),aim_id=reward_id,status=11,review_id=int(re_reward.id))
	warning_mesTable.save()
	
	return HttpResponse(str(info.img)+','+str(info.user_name)+','+str(from_id)+','+str(info.domain))

#揭榜
def uncover(request):
	reward_id=request.GET['reward_id']
	uncoverTable=Uncover(reward_id=reward_id,to=request.session['id'],status=0)
	uncoverTable.save()
	rewardTable=Reward.objects.get(id=reward_id)
	rewardTable.uncover_con=int(rewardTable.uncover_con)+1
	to=rewardTable.from_id
	rewardTable.save()
	#添加一条提醒
	warning_mesTable=Warning_mes(from_id=int(request.session['id']),to=int(to),aim_id=reward_id,status=1)
	warning_mesTable.save()
	return HttpResponse(1)

#根据reward的回复的id找到回复所在的页数
def warning_reOfReward_page(request):
	warning_id=request.GET['warning_id']
	warning=Warning_mes.objects.get(id=warning_id)
	warning.if_read=1
	warning.save()
	re_id=int(request.GET['re_id'])
	reward_id=int(request.GET['reward_id'])
	allreOfTopic_con=Reward_mes.objects.filter(reward_id=reward_id).count()
	afterreOfTopic_con=Reward_mes.objects.filter(reward_id=reward_id).filter(id__gt=re_id).count()
	page=int(math.ceil((float(allreOfTopic_con)-float(afterreOfTopic_con))/15))
	return HttpResponse(page)
